# Dungeon map interface

#   Akalabeth Re-Bourne
#   Copyright (C) 2008 Norman B. Lancaster
#
#    This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#   along with this program.  If not, see http://www.gnu.org/licenses/

# Tile information is store in $miTileFile, and the data has the follwing
# format:
# Name				(flag)	Description
# Graphic Index		(G)		Tile images start at cache[miMapGFXOfs+(G*15)], -1
#                           for no render
# Walkable			(W)		Objects are allowed to be here if 1
# Everything after the last valid field is a comment, and starts with '#' for
# no real reason.

# Configuration variables
declare -r miTileFile="./data/tiles"
declare -r miMapWidth=16
declare -r miMapHeight=16
declare -r miMapGFXOfs=0

# Globals
declare -a miCurrentMap
declare -a miTileGFX
declare -a miTileWalk

# Loads map tile information and other things needed for initialization
function MIInit
{
	local gfx walk comment i=0
	
	while read -r gfx walk comment; do
		miTileGFX[$i]="$gfx"
		miTileWalk[$i]="$walk"
		(( i++ ))
	done < "$miTileFile"
	
	return 0
}

# Loads map tile array from a map file
function MILoadMap
{
	local line idx=0

	while read line; do
		set -- $line
		while [[ -n "$1" ]]; do
			# Force values to numeric
			miCurrentMap[$idx]=$(( $1 + 0 ))
			shift
			(( idx++ ))
		done
	done

	return 0
}

# Returns the tile number for a given map location in gReturnValue
# $1 X location
# $2 Y location
function MIGetTile
{
	if (( $1 >= miMapWidth )) ||
		(( $1 < 0 )) ||
		(( $2 >= miMapHeight )) ||
		(( $2 < 0 )); then
		gReturnValue=0
	else
		gReturnValue=${miCurrentMap[$(( $2 * miMapHeight + $1 ))]}
	fi
	
	return 0
}

# Returns a given flag for a tile number in gReturnValue, see comments at the
# top of this file for flag types
# $1 Tile number
# $2 Flag type
function MIGetFlag
{
	case $2 in
		G ) gReturnValue="${miTileGFX[$1]}" ;;
		W ) gReturnValue="${miTileWalk[$1]}" ;;
		* )
			echo "EE MIGetFlag Invalid flag type" 1>&2
			exit 1 ;;
	esac
	
	return 0
}

